package com.ruoyi.project.charging.task;

import com.ruoyi.project.charging.domain.TChargingMqttMsg;
import com.ruoyi.project.charging.service.ITChargingMqttMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component("ChargingMqttTask")
public class ChargingMqttTask {
    @Autowired
    private ITChargingMqttMsgService tChargingMqttMsgService;

    /**
     * 充电桩MQTT原始报文自动转换定时任务
     */
    public void autoConvertChargingMqttMsg() {
        List<TChargingMqttMsg> tChargingMqttMsgs = tChargingMqttMsgService.selectAllTChargingMqttMsgNotConvert();
        if (tChargingMqttMsgs != null && tChargingMqttMsgs.size() > 0){
            ConcurrentLinkedQueue<TChargingMqttMsg> concurrentLinkedQueue = new ConcurrentLinkedQueue<>(tChargingMqttMsgs);
            ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
            concurrentLinkedQueue.parallelStream().forEach(tChargingMqttMsg -> {
                try {
                    // 转换报文
                    tChargingMqttMsgService.convertOriginalTChargingMqttMsg(tChargingMqttMsg);
                    // 转换成功则更新convertFlag为1
                    tChargingMqttMsgService.handleConvertSuccess(tChargingMqttMsg);
                } catch (Exception e) {
                    // 转换失败则更新convertFlag为2并记录转换失败原因
                    tChargingMqttMsgService.handleConvertFail(tChargingMqttMsg, e.getMessage());
                }
            });
            // 关闭队列
            executorService.shutdown();
        }
    }
}
